<template>
    <el-dialog :visible.sync="isShow" :title="headerTitle" @close="handleClose" center top="14vh" width="364px" append-to-body :fullscreen="fullscreen">
        <el-form :model="dialogForm" size="small" label-suffix=":" ref="detailForm" :rules="rules" label-width="80px">
            <!--              物料大类：-->
            <el-form-item :label="$t('basicData.MaterialCategory')" prop="materialMax">
                <el-select v-model="dialogForm.materialMax" style="width:100%" filterable size="small" reserve-keyword :placeholder="$t('public.inputPl')+'物料大类'">
                    <el-option v-for="item in dict.type.NYIQC_MATERIAL_MAX" :key="item.label" @click.native="changeMaterialMax(item)" :label="item.label" :value="item.label">
                    </el-option>
                </el-select>
            </el-form-item>
            <!--              物料中类：-->
            <el-form-item :label="$t('basicData.materialClass')" prop="materialMiddle" ref="materialMiddle">
                <el-select v-model="dialogForm.materialMiddle" style="width:100%" allow-create filterable size="small" reserve-keyword :placeholder="$t('public.inputPl')+'物料中类'">
                    <el-option v-for="item in dict.type.NYIQC_MATERIAL_MIDDLE" :key="item.label" @click.native="changeMaterialMiddle(item)" :label="item.label" :value="item.label">
                    </el-option>

                </el-select>
            </el-form-item>
            <!--              类型编号：-->
            <!-- <el-form-item ref="typeCode" label="类型编号" prop="typeCode">
                <el-input v-model="dialogForm.typeCode"  :placeholder="$t('public.inputPl')" clearable />
            </el-form-item> -->
            <!--              类型名称：-->
            <el-form-item ref="typeCode" :label="$t('basicData.materialSubType')" prop="typeCode">
                <el-select v-model="dialogForm.typeCode" style="width:100%" allow-create filterable size="small" reserve-keyword :placeholder="$t('public.inputPl')+'物料小类'">
                    <el-option v-for="(item,index) in materialTypeList" :key="index" :label="item.groupingCode" @click.native="changeType(item)" :value="item.groupingCode">
                    </el-option>

                </el-select>
            </el-form-item>
            <!--              描述信息：-->
            <el-form-item ref="description" :label="$t('basicData.description')" prop="description">
                <el-input v-model="dialogForm.description" type="textarea" maxlength="1000" :placeholder="$t('public.inputPl')" clearable />
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm" :loading="loading" icon="el-icon-document" size="small">{{$t('public.save')}}</el-button>
        </div>
    </el-dialog>
</template>

<script>
import {
  addMaterialType,
  getMasterialMaxMinData,
  listALLMaterialType,
  listAllMaterialTypeV2,
  updateMaterialType,
} from '@/api/basic/materialtype'
import {listALLFactory} from '@/api/basic/factory'
import EnjoySelectUser from '@/components/EnjoySelectUser'
import EnjoySelectDeptTree from '@/components/EnjoySelectDeptTree'
import FileUploadInput from '@/components/FileUploadInput'

export default {
    name: 'materialtype-detial',
    dicts: ['NYIQC_MATERIAL_MAX', 'NYIQC_MATERIAL_MIDDLE'],
    components: { EnjoySelectUser, EnjoySelectDeptTree, FileUploadInput },
    props: {
        value: {
            type: Object,
        },
        visible: {
            type: Boolean,
            default: false,
        },
        type: [String, Number], //1:新增  2：编辑 3：查看
    },
    watch: {
        value(val) {
            this.dialogForm = { ...val }
        },
        visible(val) {
            if (val) {
                // this.getFactorySelect()
            }
        },
    },
    computed: {
        isShow: {
            get() {
                return this.visible
            },
            set() {},
        },
        headerTitle() {
            const { type } = this
            let title = ''
            if (type == 1) {
                title =
                    this.$t('public.add') +
                    ' ' +
                    this.$t('basicData.materialType')
            }
            if (type == 2) {
                title =
                    this.$t('public.edit') +
                    ' ' +
                    this.$t('basicData.materialType')
            }

            return title
        },
    },
    data() {
        return {
            loading: false,
            fullscreen: false,
            materialTypeList: [],
            deviceOptions: undefined,
            factoryOptions: undefined,
            dialogForm: {},
            // 表单校验
            rules: {
                materialMax: [
                    {
                        required: true,
                        message: '物料大类不能为空',
                        trigger: 'blur',
                    },
                ],
                materialMiddle: [
                    {
                        required: true,
                        message: this.$t('formValidation.theClassInTheMaterialCannotBeEmpty'),
                        trigger: 'blur',
                    },
                ],
                // typeCode: [
                //     {
                //         required: true,
                //         message: '类型编号不能为空',
                //         trigger: 'blur',
                //     },
                // ],
                typeCode: [
                    {
                        required: true,
                        message: '类型名称不能为空',
                        trigger: 'blur',
                    },
                ],
            },
            restaurants: [],
            timeout: null,
            materialMaxOptions: [],
            materialMiddleOptions: [],
        }
    },
    mounted() {
        this.getMaterialType({}, 'materialMax')
        this.getMaterialType({ materialMax: 'all' }, 'materialMiddle')
        this.getList()
    },
    methods: {
        changeType(item) {
            this.dialogForm.typeCode = item.groupingCode
            this.dialogForm.typeName = item.groupingName
        },
        /** 发起提交 */
        submitForm: function () {
            this.loading = true
            this.$refs.detailForm.validate((valid) => {
                let action =
                    this.type == 1 ? addMaterialType : updateMaterialType
                if (valid) {
                    action(this.dialogForm).then(
                        (res) => {
                            this.loading = false
                            if (res.code == 200) {
                                this.$emit('refresh')
                                this.$modal.msgSuccess('操作成功!')
                                this.$emit('update:visible', false)
                            }
                        },
                        (err) => {
                            this.loading = false
                        }
                    )
                }
            })
        },
        getList() {
            listAllMaterialTypeV2({ hasRead: 0 }).then((res) => {
                this.materialTypeList = res.data
            })
        },
        changeMaterialMax(item) {
            this.dialogForm.maxCode = item.value
            this.dialogForm.materialMax = item.label
            if (this.dialogForm.materialMiddle) {
                this.$set(this.dialogForm, 'materialMiddle', '')
            }
            if (this.dialogForm.materialType) {
                this.$set(this.dialogForm, 'materialType', '')
            }
        },
        changeMaterialMiddle(item) {
            this.dialogForm.middleCode = item.value
            this.dialogForm.materialMiddle = item.label
        },
        handleClose(done) {
            this.$emit('update:visible', false)
        },
        getMaterialType(params, name) {
            let array = []
            getMasterialMaxMinData(params).then((res) => {
                array = res.data.map((item) => item[name])
                if (name === 'materialMax') {
                    this.materialMaxOptions = array
                } else if (name === 'materialMiddle') {
                    this.materialMiddleOptions = array
                } else {
                    this.materialOptions = array
                }
            })
        },
        handleMaterialMaxChange(e) {
            this.getMaterialType({ materialMax: e || 'all' }, 'materialMiddle')
            if (this.dialogForm.materialMiddle) {
                this.$set(this.dialogForm, 'materialMiddle', '')
            }
            if (this.dialogForm.materialType) {
                this.$set(this.dialogForm, 'materialType', '')
            }
        },
        //工厂模糊查询
        factoryRemoteMethod(val, cb) {
            listALLFactory({ factoryName: val }).then((res) => {
                this.factoryOptions = res.data.map((i) => i.deviceName)
                cb(res.data)
            })
        },
        handleFactorySelect(e) {
            this.dialogForm.factoryName = e.factoryName
            this.$refs.factoryName.$emit('el.form.blur')
        },
        handleFactoryBlur(e) {
            const { factoryOptions, dialogForm } = this
            if (!factoryOptions.includes(dialogForm.factoryName)) {
                this.dialogForm.factoryName = ''
            }
        },
        handleExpireTime(e) {
            console.log(e)
            const today = new Date().getTime()
            const val = new Date(e).getTime()
            if (val > today) {
                this.dialogForm.remDay = ~~(
                    (val - today) /
                    1000 /
                    60 /
                    60 /
                    24
                ).toFixed(1)
            } else {
                this.dialogForm.remDay = 0
            }
            this.$forceUpdate()
        },
        handleRespName(e) {
            this.dialogForm.respName = e.name
        },
        handleEmployName(e) {
            this.dialogForm.employName = e.name
        },
        handleRespDept(e) {
            this.dialogForm.respDept = e.name
        },
        materialRemoteMethod(val, cb) {
            // listALLMaterialType({materialMiddle:val}).then(res=>{
            //   this.materialOptions = res.data.map(i=>i.materialMiddle)
            //   cb(res.data)
            // })
            let restaurants = this.restaurants
            let results = val
                ? restaurants.filter(this.createStateFilter(val))
                : restaurants
            clearTimeout(this.timeout)
            this.timeout = setTimeout(() => {
                cb(results)
            }, 500 * Math.random())
        },
        createStateFilter(queryString) {
            return (state) => {
                return (
                    state.materialMiddle
                        .toLowerCase()
                        .indexOf(queryString.toLowerCase()) === 0
                )
            }
        },
        getFactorySelect() {
            listALLMaterialType().then((res) => {
                this.materialOptions = res.data.map((i) => i.materialMiddle)
                this.restaurants = res.data
            })
        },

        handleMaterialSelect(e) {
            console.log('handleMaterialSelect', e.materialMiddle)
            this.dialogForm.materialMiddle = e.materialMiddle
            this.$forceUpdate()
            this.$refs.materialMiddle.$emit('el.form.blur')
        },
        handleMaterialBlur(e) {
            console.log('handleMaterialBlur')
            const { materialOptions, dialogForm } = this
            if (!materialOptions.includes(dialogForm.materialMiddle)) {
                console.log('handleMaterialBlur includes')
                this.dialogForm.materialMiddle = ''
            }
        },
    },
}
</script>

<style scoped>
::v-deep .el-form--label-top .el-form-item__label {
    padding: 0;
}
</style>
